<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品分类" prop="catId">
        <el-select v-model="queryParams.catId" filterable placeholder="请选择商品分类">
          <el-option
              v-for="item in categoryOptions"
              :key="item.categoryId"
              :label="item.name"
              :value="item.categoryId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品编码" prop="goodsSn">
        <el-input
          v-model="queryParams.goodsSn"
          placeholder="请输入商品编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否上架" prop="isOnSale">
        <el-select v-model="queryParams.isOnSale" placeholder="请选择是否上架" clearable>
          <el-option
            v-for="dict in bl_is_on_sale"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="false">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['bl:goods:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="false"
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bl:goods:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="false"
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bl:goods:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="false"
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['bl:goods:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getMerchantList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" row-key="goodsId" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" v-if="false"/>
      <el-table-column label="封面图片" align="center" prop="originalImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.originalImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商户" align="center" prop="sysDept.deptName" />
      <el-table-column label="供应商" align="center" prop="blSuppliers.suppliersName" />
      <el-table-column label="商品分类" align="center" prop="blGoodsCategory.name" />
      <el-table-column label="商品编码" align="center" prop="goodsSn" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="点击次数" align="center" prop="clickCount" v-if="false"/>
      <el-table-column label="销售单位" align="center" prop="salesUnit">
        <template #default="scope">
          <dict-tag :options="bl_sales_unit" :value="scope.row.salesUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="进货价格" align="center" prop="goodsUprice" />
      <el-table-column label="商品备注" align="center" prop="goodsRemark" v-if="false"/>
      <el-table-column label="商品内容描述" align="center" prop="goodsContent" v-if="false"/>
      <el-table-column label="是否允许上架" align="center" prop="isOnSale">
        <template #default="scope">
          <dict-tag :options="bl_is_on_sale" :value="scope.row.isOnSale"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" v-if="false"/>
      <el-table-column label="是否新品" align="center" prop="isNew" v-if="false">
        <template #default="scope">
          <dict-tag :options="bl_is_on_sale" :value="scope.row.isNew"/>
        </template>
      </el-table-column>
      <el-table-column label="是否热门" align="center" prop="isHot" v-if="false">
        <template #default="scope">
          <dict-tag :options="bl_is_on_sale" :value="scope.row.isHot"/>
        </template>
      </el-table-column>
      <el-table-column label="包装单位" align="center" prop="packagingUnit" v-if="false"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="false">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['bl:goods:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bl:goods:remove']">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="库存" align="center" class-name="small-padding fixed-width" fixed="right" width="80">
        <template #default="scope">
          <router-link :to="'/bl/merchant-goods-store/index/' + scope.row.goodsId" class="link-type">
            <span>库存详情</span>
          </router-link>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getMerchantList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="goodsRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
           <el-col :span="12">
            <el-form-item label="商户" prop="deptId">
                <el-select v-model="form.deptId" filterable placeholder="请选择" @change="handleDeptChange">
                  <el-option
                      v-for="item in deptOptions"
                      :key="item.deptId"
                      :label="item.deptName"
                      :value="item.deptId"
                  ></el-option>
                </el-select>
            </el-form-item>
           </el-col> 
           <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
                <el-select v-model="form.supplierId" filterable placeholder="请选择">
                  <el-option
                      v-for="item in suppliersOptions"
                      :key="item.supplierId"
                      :label="item.suppliersName"
                      :value="item.supplierId"
                  ></el-option>
                </el-select>
            </el-form-item>
          </el-col> 
        </el-row>
        <el-row>
           <el-col :span="12">
              <el-form-item label="商品分类" prop="catId">
                <el-select v-model="form.catId" filterable placeholder="请选择商品分类">
                  <el-option
                      v-for="item in categoryOptions"
                      :key="item.categoryId"
                      :label="item.name"
                      :value="item.categoryId"
                  ></el-option>
                </el-select>
              </el-form-item>
          </el-col> 
          <el-col :span="12">
              <el-form-item label="商品编码" prop="goodsSn">
                <el-input v-model="form.goodsSn" placeholder="请输入商品编码" />
              </el-form-item>
           </el-col> 
        </el-row>
        <el-row>
           <el-col :span="12">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col> 
          <el-col :span="12">
            <el-form-item label="销售单位" prop="salesUnit">
              <el-select v-model="form.salesUnit" placeholder="请选择销售单位" clearable>
                <el-option
                  v-for="dict in bl_sales_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col> 
        </el-row>
        <el-row>
          <el-col :span="12">
          <el-form-item label="销售价格" prop="goodsUprice">
                <el-input v-model="form.goodsUprice" placeholder="请输入销售价格如60.00" />
              </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item label="是否上架" prop="isOnSale">
              <el-select v-model="form.isOnSale" placeholder="请选择是否上架">
                <el-option
                  v-for="dict in bl_is_on_sale"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> 
          <el-col :span="12" v-if="false">
            <el-form-item label="商品备注" prop="goodsRemark">
              <el-input v-model="form.goodsRemark" placeholder="请输入商品备注" />
            </el-form-item>
          </el-col> 
        </el-row>
        <el-form-item label="商品内容描述" label-width="100">
          <editor v-model="form.goodsContent" :min-height="192"/>
          <!-- <vue-ueditor-wrap v-model="form.goodsContent" :config="editorConfig"></vue-ueditor-wrap> -->
        </el-form-item>
        <el-form-item label="商品封面图片" prop="originalImg" label-width="100">
          <image-upload v-model="form.originalImg" :limit="1"/>
        </el-form-item>
        <el-form-item label="商品轮播图" prop="carouselImg" label-width="100">
          <image-upload v-model="form.carouselImg"/>
        </el-form-item>
        <el-row v-show="false">
           <el-col :span="12">
              <el-form-item label="是否新品" prop="isNew" v-show="false">
                <el-select v-model="form.isNew" placeholder="请选择是否新品">
                  <el-option
                    v-for="dict in bl_is_on_sale"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>
           </el-col> 
           <el-col :span="12">
            <el-form-item label="是否热门" prop="isHot" v-show="false">
              <el-select v-model="form.isHot" placeholder="请选择是否热门">
                <el-option
                  v-for="dict in bl_is_on_sale"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> 
        </el-row>
        <el-form-item label="包装单位" prop="packagingUnit" v-show="false">
          <el-input v-model="form.packagingUnit" placeholder="请输入包装单位" />
        </el-form-item>
        <el-form-item label="排序" prop="sort"  v-show="false">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import { listMerchantGoods, getGoods, delGoods, addGoods, updateGoods } from "@/api/bl/goods/goods";

const { proxy } = getCurrentInstance();
const { bl_is_on_sale, bl_sales_unit } = proxy.useDict('bl_is_on_sale' , 'bl_sales_unit');
import { listCategory } from "@/api/bl/category";
import { listDeptAll } from "@/api/bl/dept";
import { listBlSuppliers } from "@/api/bl/suppliers";

const goodsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const categoryOptions = ref([]);
const deptOptions = ref([]);
const suppliersOptions = ref([]);

const editorConfig = reactive({
   // 设置编辑器不自动被内容撑高
      autoHeightEnabled: false,
        // 初始容器高度
      initialFrameHeight: 200,
        // 初始容器宽度
      initialFrameWidth: "100%",
      UEDITOR_HOME_URL: '/UEditor/', // 访问 UEditor 静态资源的根路径，可参考常见问题1
      serverUrl: 'http://localhost:8081/prod-api/ueditor/uploadimage', // 服务端接口
      //serverUrl: 'http://localhost:8081/prod-api/ueditor/uploadimage', // 服务端接口
      toolbars: [[
          'fullscreen', 'source', '|', 'undo', 'redo', '|',
          'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
          'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
          'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
          'directionalityltr', 'directionalityrtl', 'indent', '|',
          'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
          'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
          'simpleupload', 'emotion'
      ]]
    });

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    goodsSn: null,
    goodsName: null,
    salesUnit: null,
    catId:null,
    isOnSale:null,
  },
  rules: {
    deptId: [
      { required: true, message: "商户不能为空", trigger: "blur" }
    ],
    supplierId: [
      { required: true, message: "供应商不能为空", trigger: "blur" }
    ],
    goodsSn: [
      { required: true, message: "商品编码不能为空", trigger: "blur" }
    ],
    goodsName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" }
    ],
    salesUnit: [
      { required: true, message: "销售单位不能为空", trigger: "blur" }
    ],
    goodsUprice: [
      {required: true, message: "商品价格不能为空", trigger: "blur" },
      {
          pattern: /(^[1-9]\d{0,9}(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
          message: '价格格式设置错误'
      }
    ],
    isOnSale: [
      { required: true, message: "是否上架不能为空", trigger: "blur" }
    ],
  },
  querySuppliersParams: {
    pageNum: 1,
    pageSize: 100000,
    deptId: null,
  },
});

const { queryParams, form, rules, querySuppliersParams } = toRefs(data);

/** 查询商品信息列表 */
function getMerchantList() {
  loading.value = true;
  listMerchantGoods(queryParams.value).then(response => {
    goodsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    goodsId: null,
    catId: null,
    goodsSn: null,
    goodsName: null,
    clickCount: null,
    salesUnit: null,
    goodsUprice: null,
    goodsRemark: null,
    goodsContent: undefined,
    originalImg: null,
    carouselImg: null,
    isOnSale: null,
    sort: null,
    isNew: null,
    isHot: null,
    packagingUnit: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("goodsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getMerchantList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.goodsId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getSuppliersList(row.deptId)
  sleep(1000); // 休眠2秒
  const _goodsId = row.goodsId || ids.value
  getGoods(_goodsId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商品";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodsRef"].validate(valid => {
    if (valid) {
      if (form.value.goodsId != null) {
        updateGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getMerchantList();
        });
      } else {
        addGoods(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getMerchantList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _goodsIds = row.goodsId || ids.value;
  const _goodsName = row.goodsName;
  proxy.$modal.confirm('是否确认删除商品信息为"' + _goodsName + '"的数据项？').then(function() {
    return delGoods(_goodsIds);
  }).then(() => {
    getMerchantList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('bl/goods/export', {
    ...queryParams.value
  }, `goods_${new Date().getTime()}.xlsx`)
}


/** 查询商品分类列表 */
function getCategoryList() {
  loading.value = true;
  listCategory(queryParams.value).then(response => {
    categoryOptions.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询商户信息列表 */
function getDeptAllList() {
listDeptAll(queryParams.value).then(response => {
  let deptListTmp = response.data;
  deptOptions.value = deptListTmp.filter(item => item.deptId !== 100);
});
}

/** 查询供应商列表 */
function getSuppliersList(deptId) {
  querySuppliersParams.value.deptId = deptId;
  listBlSuppliers(querySuppliersParams.value).then(response => {
    suppliersOptions.value = response.rows;
  });
}

/** 商户选择变动时 */
function handleDeptChange(){
  let deptId = form.value.deptId;
  getSuppliersList(deptId);
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

getMerchantList();
getCategoryList();
//getDeptAllList();
</script>
